import 'package:cc_sdk/models/comment_model.dart';
import 'package:cc_sdk/models/comment_statistics.dart';
import 'package:cc_sdk/models/member_info.dart';
import 'package:cc_sdk/models/pager_result.dart';
import 'package:cc_sdk/services/comment_service.dart';
import 'package:cc_sdk/widgets/badge.dart';
import 'package:cc_sdk/widgets/comment_list_widget.dart';
import 'package:cc_sdk/widgets/progress_button.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'bottom_sheet.dart';
import 'comment_reply_widget.dart';

class CommentController {
  final OnStatisticsEvent onStatisticsEvent;
  final GetMemberInfo getMemberInfo;
  final Function onLogin;
  final Function onLikeClick;
  final Function onShareClick;

  CommentController({
    this.onStatisticsEvent,
    this.getMemberInfo,
    this.onLogin,
    this.onLikeClick,
    this.onShareClick,
  });
}

class CommentWidget extends StatefulWidget {
  final int parentId;
  final String outId;
  final Widget header;
  final int memberId;

  final CommentController controller;

  const CommentWidget({
    Key key,
    this.controller,
    this.memberId,
    this.parentId,
    this.outId,
    this.header,
  }) : super(key: key);

  @override
  _CommentWidgetWidgetState createState() =>
      new _CommentWidgetWidgetState(parentId, outId);
}

class _CommentWidgetWidgetState extends State<CommentWidget> {
  final Color icoColor = Color(0xff646464);
  final int parentId;
  final String outId;
  int recordCount = 0;
  bool showReply = false;
  CommentStatistics _statistics;
  CommentListController _listController;

  TextEditingController _commentController = TextEditingController();

  _CommentWidgetWidgetState(this.parentId, this.outId) {}

  @override
  void initState() {
    super.initState();

    _listController = new CommentListController(
      onStatisticsEvent: (CommentStatistics statistics) {
        _statistics = statistics;
        if (widget.controller != null &&
            widget.controller.onStatisticsEvent != null) {
          widget.controller.onStatisticsEvent(statistics);
        }
        setState(() {});
      },
      getMemberInfo: widget.controller.getMemberInfo,
      onLogin: widget.controller.onLogin,
    );
    _listController.pagerStream.listen(onPagerStream);
  }

  @override
  void dispose() {
    super.dispose();
    _listController.dispose();
  }

  void onPagerStream(PagerResult<CommentModel> pager) {
    this.recordCount = pager.recordCount;
    setState(() {});
  }

  Future onReplyClosed(CommentModel model) async {
    if (model != null) {
      _listController.insert(model);
      _commentController.clear();
      this.recordCount++;
      setState(() {});
    }
  }

  Future _showReply() async {
    if (widget.memberId < 1) {
      widget.controller.onLogin();
      return;
    }
    var model = await showDialog(
      context: context,
      builder: (_) =>
          Scaffold(
            backgroundColor: Colors.transparent,
            resizeToAvoidBottomInset: false,
            body: CommentReplyWidget(
              parentId: parentId,
              outId: outId,
              memberId: widget.memberId,
              controller: _commentController,
              callback: (model) {
                Navigator.pop(context, model);
              },
            ),
          ),
    );
    onReplyClosed(model);
//    Navigator.of(context).push(new MaterialPageRoute<Null>(
//        builder: (_) => MaterialApp(
//
//              home: Scaffold(
//                backgroundColor: Colors.transparent,
//                body: CommentReplyWidget(
//                  parentId: parentId,
//                  outId: outId,
//                  controller: _commentController,
//                  callback: (model) => {},
//                ),
//              ),
//            ),
//        fullscreenDialog: true));
  }

  Widget _buildComment() {
    return GestureDetector(
      onTap: () {
        _listController.goTop();
      },
      child: Badge.left(
        value: this.recordCount.toString(),
        borderSize: 0,
        positionTop: 5,
        positionRight: 5,
        textStyle: TextStyle(fontSize: 8, color: Colors.white),
        child: Container(
          padding: EdgeInsets.all(10),
          child: Icon(
            Icons.comment,
            size: 30,
            color: icoColor,
          ),
        ),
      ),
    );
  }

  Widget _buildNormalIcon(Color color, IconData icon,
      GestureTapCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(10),
        child: Icon(
          icon,
          size: 30,
          color: color,
        ),
      ),
    );
  }

//  Widget _buildFavorites() {
//    Color checkedColor = widget.hasFavorites ? Colors.yellow : icoColor;
//    return _buildNormalIcon(checkedColor, Icons.star, () {
//      if (widget.onFavoritesClick != null)
//        widget.onFavoritesClick();
//    });
//  }

  Widget _buildLike() {
    var hitColor = _statistics != null && _statistics.myLike
        ? Color(0xFFcf0909)
        : icoColor;
    return _buildNormalIcon(hitColor, Icons.thumb_up, () {
      if (widget.memberId > 0) {
        if (_statistics.myLike) {
          CommentService.internal().unlike(outId, widget.memberId);
        } else {
          CommentService.internal().like(outId, widget.memberId);
        }
        _statistics.myLike = !_statistics.myLike;
        setState(() {});
      } else {
        widget.controller.onLogin();
      }
    });
  }

  Widget _buildShare() {
    return _buildNormalIcon(icoColor, Icons.share, () {
      if (widget.controller != null && widget.controller.onShareClick != null)
        widget.controller.onShareClick();
    });
  }

  @override
  Widget build(BuildContext context) {
    Color icoColor = Color(int.parse("ff646464", radix: 16));
    return Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: CommentListWidget(
                parentId: parentId,
                outId: outId,
                controller: _listController,
                memberId: widget.memberId,
                header: widget.header),
          ),
          Container(
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: Color(int.parse("ffd8d8d8", radix: 16)),
                ),
              ),
            ),
            height: 50,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: GestureDetector(
                    onTap: _showReply,
                    child: Container(
                      padding: EdgeInsets.all(5),
                      margin: EdgeInsets.only(left: 10, right: 10),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Color(int.parse("ffe8e8e8", radix: 16)),
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                        color: Color(int.parse("fff4f5f6", radix: 16)),
                      ),
                      child: Row(
                        children: <Widget>[
                          Icon(
                            Icons.edit,
                            color: icoColor,
                          ),
                          Text("写评论"),
                        ],
                      ),
                    ),
                  ),
                ),
                _buildComment(),
//                _buildFavorites(),
                _buildLike(),
                _buildShare(),
              ],
            ),
          )
        ],
      ),
    );
  }
}
